package com.cjl.dental_clinic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjl.dental_clinic.Req.PatientMedReq;
import com.cjl.dental_clinic.Req.PatientReq;
import com.cjl.dental_clinic.entity.Medicine;
import com.cjl.dental_clinic.entity.Patient;
import com.cjl.dental_clinic.entity.Prescriptiondetail;
import com.cjl.dental_clinic.mapper.PatientMapper;
import com.cjl.dental_clinic.service.MedicineService;
import com.cjl.dental_clinic.service.PatientService;
import com.cjl.dental_clinic.service.PrescriptiondetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description:
 * @author: cjl
 * @time: 2024/04/09 14:06
 */
@Service
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements PatientService {
    @Autowired
    private MedicineService medicineService;
    @Autowired
    private PrescriptiondetailService prescriptiondetailService;
    @Override
    public Boolean updateStatus(Integer id, Integer status) {
        Patient patient = baseMapper.selectById(id);
        return baseMapper.updateById(patient.setVisitstatus(status))>0;
    }

    /**
     * 获取用户列表
     * @param name
     * @return
     */
    @Override
    public List<PatientReq> listPatient(String name) {
        List<PatientReq> reqs = baseMapper.listPatient(name);
        for (PatientReq req : reqs) {
            req.setMedicineList(medicineService.listMedicine(req.getPreId()));
        }
        return reqs;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean med(PatientMedReq patientMedReq) {
        // 通过处方id删除所有药品详情
        prescriptiondetailService.remove(new QueryWrapper<Prescriptiondetail>().eq("prescription_id",patientMedReq.getPreId()));
        // 重新添加药品详情
        for (Integer medId : patientMedReq.getMedIds()) {
            Prescriptiondetail prescriptiondetail = new Prescriptiondetail();
            prescriptiondetail.setMedicineId(medId);
            prescriptiondetail.setQuantity(1);
            prescriptiondetail.setPrescriptionId(patientMedReq.getPreId());
            prescriptiondetail.initCreateUser();
            Medicine byId = medicineService.getById(medId);
            byId.setStockQuantity(byId.getStockQuantity()-1);
            medicineService.updateById(byId);
            prescriptiondetailService.save(prescriptiondetail);
        }
        return prescriptiondetailService.count(new QueryWrapper<Prescriptiondetail>().eq("prescription_id",patientMedReq.getPreId()))>0;
    }
}
